library(tidyverse) # for data cleaning and plotting
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ ggplot2 3.3.3 ✓ purrr 0.3.4
## ✓ tibble 3.0.5 ✓ dplyr 1.0.3
## ✓ tidyr 1.1.2 ✓ stringr 1.4.0
## ✓ readr 1.4.0 ✓ forcats 0.5.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
library(lubridate) # for date manipulation
##
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
library(openintro) # for the abbr2state() function
## Loading required package: airports
## Loading required package: cherryblossom
## Loading required package: usdata
library(palmerpenguins)# for Palmer penguin data
library(maps) # for map data
##
## Attaching package: 'maps'
## The following object is masked from 'package:purrr':
##
## map
library(ggmap) # for mapping points on maps
## Google's Terms of Service: https://cloud.google.com/maps-platform/terms/.
## Please cite ggmap if you use it! See citation("ggmap") for details.
library(gplots) # for col2hex() function
##
## Attaching package: 'gplots'
## The following object is masked from 'package:stats':
##
## lowess
library(RColorBrewer) # for color palettes
library(sf) # for working with spatial data
## Linking to GEOS 3.8.1, GDAL 3.1.4, PROJ 6.3.1
library(leaflet) # for highly customizable mapping
library(carData) # for Minneapolis police stops data
library(ggthemes) # for more themes (including theme_map())
theme_set(theme_minimal())
# Starbucks locations
Starbucks <- read_csv("https://www.macalester.edu/~ajohns24/Data/Starbucks.csv")
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## Brand = col_character(),
## `Store Number` = col_character(),
## `Store Name` = col_character(),
## `Ownership Type` = col_character(),
## `Street Address` = col_character(),
## City = col_character(),
## `State/Province` = col_character(),
## Country = col_character(),
## Postcode = col_character(),
## `Phone Number` = col_character(),
## Timezone = col_character(),
## Longitude = col_double(),
## Latitude = col_double()
## )
starbucks_us_by_state <- Starbucks %>%
filter(Country == "US") %>%
count(`State/Province`) %>%
mutate(state_name = str_to_lower(abbr2state(`State/Province`)))
# Lisa's favorite St. Paul places - example for you to create your own data
favorite_stp_by_lisa <- tibble(
place = c("Home", "Macalester College", "Adams Spanish Immersion",
"Spirit Gymnastics", "Bama & Bapa", "Now Bikes",
"Dance Spectrum", "Pizza Luce", "Brunson's"),
long = c(-93.1405743, -93.1712321, -93.1451796,
-93.1650563, -93.1542883, -93.1696608,
-93.1393172, -93.1524256, -93.0753863),
lat = c(44.950576, 44.9378965, 44.9237914,
44.9654609, 44.9295072, 44.9436813,
44.9399922, 44.9468848, 44.9700727)
)
#COVID-19 data from the New York Times
covid19 <- read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv")
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## date = col_date(format = ""),
## state = col_character(),
## fips = col_character(),
## cases = col_double(),
## deaths = col_double()
## )
For ALL graphs, you should include appropriate labels.
When you are finished with ALL the exercises, uncomment the options at the top so your document looks nicer. Don’t do it before then, or else you might miss some important warnings and messages.
These exercises will reiterate what you learned in the “Mapping data with R” tutorial. If you haven’t gone through the tutorial yet, you should do that first.
ggmap)Starbucks locations to a world map. Add an aesthetic to the world map that sets the color of the points according to the ownership type. What, if anything, can you deduce from this visualization?# Get the map information
world <- get_stamenmap(
bbox = c(left = -180, bottom = -57, right = 179, top = 82.1),
maptype = "terrain",
zoom = 2)
## Source : http://tile.stamen.com/terrain/2/0/0.png
## Source : http://tile.stamen.com/terrain/2/1/0.png
## Source : http://tile.stamen.com/terrain/2/2/0.png
## Source : http://tile.stamen.com/terrain/2/3/0.png
## Source : http://tile.stamen.com/terrain/2/0/1.png
## Source : http://tile.stamen.com/terrain/2/1/1.png
## Source : http://tile.stamen.com/terrain/2/2/1.png
## Source : http://tile.stamen.com/terrain/2/3/1.png
## Source : http://tile.stamen.com/terrain/2/0/2.png
## Source : http://tile.stamen.com/terrain/2/1/2.png
## Source : http://tile.stamen.com/terrain/2/2/2.png
## Source : http://tile.stamen.com/terrain/2/3/2.png
# Plot the points on the map
ggmap(world) + # creates the map "background"
geom_point(data = Starbucks,
aes(x = Longitude, y = Latitude, color = `Ownership Type`), alpha = .3, size = .1) +
theme_map()
## Warning: Removed 1 rows containing missing values (geom_point).
starbucks_mn <- Starbucks %>%
filter(Country == "US", `State/Province` == "MN")
minneapolis <- get_stamenmap(
bbox = c(left = -93.47, bottom = 44.79, right = -92.76, top = 45.13),
maptype = "terrain",
zoom = 11)
## Source : http://tile.stamen.com/terrain/11/492/735.png
## Source : http://tile.stamen.com/terrain/11/493/735.png
## Source : http://tile.stamen.com/terrain/11/494/735.png
## Source : http://tile.stamen.com/terrain/11/495/735.png
## Source : http://tile.stamen.com/terrain/11/496/735.png
## Source : http://tile.stamen.com/terrain/11/492/736.png
## Source : http://tile.stamen.com/terrain/11/493/736.png
## Source : http://tile.stamen.com/terrain/11/494/736.png
## Source : http://tile.stamen.com/terrain/11/495/736.png
## Source : http://tile.stamen.com/terrain/11/496/736.png
## Source : http://tile.stamen.com/terrain/11/492/737.png
## Source : http://tile.stamen.com/terrain/11/493/737.png
## Source : http://tile.stamen.com/terrain/11/494/737.png
## Source : http://tile.stamen.com/terrain/11/495/737.png
## Source : http://tile.stamen.com/terrain/11/496/737.png
## Source : http://tile.stamen.com/terrain/11/492/738.png
## Source : http://tile.stamen.com/terrain/11/493/738.png
## Source : http://tile.stamen.com/terrain/11/494/738.png
## Source : http://tile.stamen.com/terrain/11/495/738.png
## Source : http://tile.stamen.com/terrain/11/496/738.png
ggmap(minneapolis) +
geom_point(data = starbucks_mn,
aes(x = Longitude, y = Latitude),
alpha = 1,
size = 1,
color = "forestgreen") +
theme_map()
## Warning: Removed 75 rows containing missing values (geom_point).
starbucks_us_by_state <- Starbucks %>%
filter(Country == "US") %>%
count(`State/Province`) %>%
mutate(state_name = str_to_lower(abbr2state(`State/Province`)))
states_map <- map_data("state")
world <- get_stamenmap(
bbox = c(left = -103, bottom = 40, right = -85, top = 52),
maptype = "terrain",
zoom = 5)
## Source : http://tile.stamen.com/terrain/5/6/10.png
## Source : http://tile.stamen.com/terrain/5/7/10.png
## Source : http://tile.stamen.com/terrain/5/8/10.png
## Source : http://tile.stamen.com/terrain/5/6/11.png
## Source : http://tile.stamen.com/terrain/5/7/11.png
## Source : http://tile.stamen.com/terrain/5/8/11.png
## Source : http://tile.stamen.com/terrain/5/6/12.png
## Source : http://tile.stamen.com/terrain/5/7/12.png
## Source : http://tile.stamen.com/terrain/5/8/12.png
ggmap(world)
\(~\)
get_stamenmap() in help and look at maptype). Include a map with one of the other map types.world <- get_stamenmap(
bbox = c(left = -103, bottom = 40, right = -85, top = 52),
maptype = "watercolor",
zoom = 5)
## Source : http://tile.stamen.com/watercolor/5/6/10.jpg
## Source : http://tile.stamen.com/watercolor/5/7/10.jpg
## Source : http://tile.stamen.com/watercolor/5/8/10.jpg
## Source : http://tile.stamen.com/watercolor/5/6/11.jpg
## Source : http://tile.stamen.com/watercolor/5/7/11.jpg
## Source : http://tile.stamen.com/watercolor/5/8/11.jpg
## Source : http://tile.stamen.com/watercolor/5/6/12.jpg
## Source : http://tile.stamen.com/watercolor/5/7/12.jpg
## Source : http://tile.stamen.com/watercolor/5/8/12.jpg
ggmap(world)
\(~\)
annotate() function (see ggplot2 cheatsheet).world <- get_stamenmap(
bbox = c(left = -103, bottom = 40, right = -85, top = 52),
maptype = "toner",
zoom = 5)
## Source : http://tile.stamen.com/toner/5/6/10.png
## Source : http://tile.stamen.com/toner/5/7/10.png
## Source : http://tile.stamen.com/toner/5/8/10.png
## Source : http://tile.stamen.com/toner/5/6/11.png
## Source : http://tile.stamen.com/toner/5/7/11.png
## Source : http://tile.stamen.com/toner/5/8/11.png
## Source : http://tile.stamen.com/toner/5/6/12.png
## Source : http://tile.stamen.com/toner/5/7/12.png
## Source : http://tile.stamen.com/toner/5/8/12.png
ggmap(world) +
geom_point(aes(x = -93, y = 44.7), color = "red") +
geom_text(aes(x = -93, y = 44.4, label = "Macalester College"))
\(~\)
geom_map())The example I showed in the tutorial did not account for population of each state in the map. In the code below, a new variable is created, starbucks_per_10000, that gives the number of Starbucks per 10,000 people. It is in the starbucks_with_2018_pop_est dataset.
census_pop_est_2018 <- read_csv("https://www.dropbox.com/s/6txwv3b4ng7pepe/us_census_2018_state_pop_est.csv?dl=1") %>%
separate(state, into = c("dot","state"), extra = "merge") %>%
select(-dot) %>%
mutate(state = str_to_lower(state))
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## state = col_character(),
## est_pop_2018 = col_double()
## )
starbucks_with_2018_pop_est <-
starbucks_us_by_state %>%
left_join(census_pop_est_2018,
by = c("state_name" = "state")) %>%
mutate(starbucks_per_10000 = (n/est_pop_2018)*10000)
dplyr review: Look through the code above and describe what each line of code does.\(~\)
states_map <- map_data("state")
starbucks_with_2018_pop_est %>%
ggplot() +
geom_map(map = states_map,
aes(map_id = state_name,
fill = starbucks_per_10000)) +
expand_limits(x = states_map$long, y = states_map$lat) +
geom_point(data = Starbucks %>% filter(`Country` == "US",
`State/Province` != "AK",
`State/Province` != "HI"),
aes(x = Longitude, y = Latitude),
size = .05,
alpha = .2,
color = "gold") +
scale_fill_gradient2(low = "lightskyblue1", mid = "paleturquoise2", high = "forestgreen") +
labs(title = "Starbucks location per 10,000 people in the US",
x = "Longitude",
y = "Latitude",
caption = "Jennifer Huang",
fill = "Starbucks per 10,000") +
theme_map() +
theme(legend.background = element_blank())
\(~\) ### A few of your favorite things (leaflet)
tibble() function that has 10-15 rows of your favorite places. The columns will be the name of the location, the latitude, the longitude, and a column that indicates if it is in your top 3 favorite locations or not. For an example of how to use tibble(), look at the favorite_stp_by_lisa I created in the data R code chunk at the beginning.fav_taiwan_jen <- tibble(
place = c("ShiFen Old Street", "HouTong Cat Village", "JiouFen Mountain Town",
"TianMu District", "TamSui District", "Home",
"LungShan Temple", "HuaShan 1914 Creative Park",
"ZhongXiao East Road", "Taipei 101"),
long = c(121.7767, 121.8275, 121.8463,
121.5341, 121.5150, 121.4434,
121.4999, 121.5293,
121.5429, 121.5645),
lat = c(25.0427, 25.0870, 25.1092,
25.1157, 25.1152, 25.1720,
25.0372, 25.0441,
25.0411, 25.0340),
TopThree = place %in% c("JiouFen Mountain Town", "TamSui District", "ZhongXiao East Road")
)
Create a leaflet map that uses circles to indicate your favorite places. Label them with the name of the place. Choose the base map you like best. Color your 3 favorite places differently than the ones that are not in your top 3 (HINT: colorFactor()). Add a legend that explains what the colors mean.
Connect all your locations together with a line in a meaningful way (you may need to order them differently in the original data).
If there are other variables you want to add that could enhance your plot, do that now.
pal_col <- colorFactor("viridis", domain = fav_taiwan_jen$TopThree)
leaflet(data = fav_taiwan_jen) %>%
addTiles() %>%
addCircles(lng = ~long,
lat = ~lat,
opacity = 1,
radius = 50,
color = ~pal_col(TopThree)) %>%
addPolylines(lng = ~long,
lat = ~lat,
color = col2hex("darkblue")) %>%
addLegend(position = c("topright"),
pal = pal_col,
values = ~TopThree,
opacity = 1)
\(~\)
This section will revisit some datasets we have used previously and bring in a mapping component.
The data come from Washington, DC and cover the last quarter of 2014.
Two data tables are available:
Trips contains records of individual rentalsStations gives the locations of the bike rental stationsHere is the code to read in the data. We do this a little differently than usualy, which is why it is included here rather than at the top of this file. To avoid repeatedly re-reading the files, start the data import chunk with {r cache = TRUE} rather than the usual {r}. This code reads in the large dataset right away.
data_site <-
"https://www.macalester.edu/~dshuman1/data/112/2014-Q4-Trips-History-Data.rds"
Trips <- readRDS(gzcon(url(data_site)))
Stations<-read_csv("http://www.macalester.edu/~dshuman1/data/112/DC-Stations.csv")
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## name = col_character(),
## lat = col_double(),
## long = col_double(),
## nbBikes = col_double(),
## nbEmptyDocks = col_double()
## )
Stations to make a visualization of the total number of departures from each station in the Trips data. Use either color or size to show the variation in number of departures. This time, plot the points on top of a map. Use any of the mapping tools you’d like.DC_map <- get_stamenmap(
bbox = c(left = -77.2035, bottom = 38.7840,
right = -76.8498, top = 39.0126),
maptype = "terrain",
zoom = 12)
## Source : http://tile.stamen.com/terrain/12/1169/1565.png
## Source : http://tile.stamen.com/terrain/12/1170/1565.png
## Source : http://tile.stamen.com/terrain/12/1171/1565.png
## Source : http://tile.stamen.com/terrain/12/1172/1565.png
## Source : http://tile.stamen.com/terrain/12/1173/1565.png
## Source : http://tile.stamen.com/terrain/12/1169/1566.png
## Source : http://tile.stamen.com/terrain/12/1170/1566.png
## Source : http://tile.stamen.com/terrain/12/1171/1566.png
## Source : http://tile.stamen.com/terrain/12/1172/1566.png
## Source : http://tile.stamen.com/terrain/12/1173/1566.png
## Source : http://tile.stamen.com/terrain/12/1169/1567.png
## Source : http://tile.stamen.com/terrain/12/1170/1567.png
## Source : http://tile.stamen.com/terrain/12/1171/1567.png
## Source : http://tile.stamen.com/terrain/12/1172/1567.png
## Source : http://tile.stamen.com/terrain/12/1173/1567.png
## Source : http://tile.stamen.com/terrain/12/1169/1568.png
## Source : http://tile.stamen.com/terrain/12/1170/1568.png
## Source : http://tile.stamen.com/terrain/12/1171/1568.png
## Source : http://tile.stamen.com/terrain/12/1172/1568.png
## Source : http://tile.stamen.com/terrain/12/1173/1568.png
station_trips <- Trips %>%
mutate(name = sstation) %>%
left_join(Stations,
by = c("name")) %>%
group_by(lat, long) %>%
summarize(freq_stations = n())
## `summarise()` has grouped output by 'lat'. You can override using the `.groups` argument.
ggmap(DC_map) +
geom_point(data = station_trips,
aes(x = long, y = lat, color = freq_stations),
alpha = 1,
size = 1) +
scale_color_viridis_c() +
labs(title = "Totale number of departures from each bike station in DC",
col = "Frequency") +
theme_map() +
theme(legend.background = element_blank())
## Warning: Removed 22 rows containing missing values (geom_point).
departures <- Trips %>%
left_join(Stations, by = c("estation" = "name")) %>%
group_by(lat, long) %>%
summarize(n = n(), probability = mean(client == "Casual"))
## `summarise()` has grouped output by 'lat'. You can override using the `.groups` argument.
ggmap(DC_map) +
geom_point(data = departures,
aes(x = long, y = lat, color = probability),
alpha = 1,
size = 1) +
scale_color_viridis_c() +
labs(title = "Areas in DC with high percentage of departures by casual bike users",
col = "Percentage of client type") +
theme_map() +
theme(legend.background = element_blank())
## Warning: Removed 22 rows containing missing values (geom_point).
The following exercises will use the COVID-19 data from the NYT.
states_map <- map_data("state")
covid19 %>%
group_by(state) %>%
summarize(most_recent_case = max(cases)) %>%
mutate(state = str_to_lower(state)) %>%
# since its cumulative, we can use max(), if not we can't
ggplot() +
geom_map(map = states_map,
aes(map_id = state, fill = most_recent_case)) +
scale_fill_viridis_c() +
expand_limits(x = states_map$long, y = states_map$lat) +
theme_map()
states_map <- map_data("state")
census_pop_est_2018 <- read_csv("https://www.dropbox.com/s/6txwv3b4ng7pepe/us_census_2018_state_pop_est.csv?dl=1") %>%
separate(state, into = c("dot","state"), extra = "merge") %>%
select(-dot) %>%
mutate(state = str_to_lower(state))
##
## ── Column specification ────────────────────────────────────────────────────────
## cols(
## state = col_character(),
## est_pop_2018 = col_double()
## )
covid_with_2018_pop_est <-
covid19 %>%
mutate(state = str_to_lower(state)) %>%
left_join(census_pop_est_2018,
by = c("state" = "state")) %>%
mutate(most_recent_case = max(cases),
covid_per_10000 = (most_recent_case/est_pop_2018)*10000) %>%
ggplot() +
geom_map(map = states_map,
aes(map_id = state, fill = covid_per_10000)) +
scale_fill_viridis_c() +
expand_limits(x = states_map$long, y = states_map$lat) +
theme_map()
covid_with_2018_pop_est
\(~\)
These exercises use the datasets MplsStops and MplsDemo from the carData library. Search for them in Help to find out more information.
MplsStops dataset to find out how many stops there were for each neighborhood and the proportion of stops that were for a suspicious vehicle or person. Sort the results from most to least number of stops. Save this as a dataset called mpls_suspicious and display the table.mpls_suspicious <- MplsStops %>%
mutate(problem_numeric = problem %in% c("suspicious")) %>%
group_by(neighborhood) %>%
summarize(number_of_stops = n(),
prop_sus = mean(problem_numeric))
mpls_suspicious
leaflet map and the MplsStops dataset to display each of the stops on a map as a small point. Color the points differently depending on whether they were for suspicious vehicle/person or a traffic stop (the problem variable). HINTS: use addCircle, set stroke = FAlSE, use colorFactor() to create a palette.pal_police <- colorFactor("viridis", domain = MplsStops$problem)
MplsStops %>%
leaflet() %>%
addTiles() %>%
addCircles(lng = ~long,
lat = ~lat,
opacity = 0.5,
radius = 2,
color = ~pal_police(problem)) %>% #apply color created to problem variable
addLegend(position = c("topright"),
pal = pal_police,
values = ~problem,
opacity = 1)
eval=FALSE. Although it looks like it only links to the .sph file, you need the entire folder of files to create the mpls_nbhd data set. These data contain information about the geometries of the Minneapolis neighborhoods. Using the mpls_nbhd dataset as the base file, join the mpls_suspicious and MplsDemo datasets to it by neighborhood (careful, they are named different things in the different files). Call this new dataset mpls_all.mpls_nbhd <- st_read("Minneapolis_Neighborhoods/Minneapolis_Neighborhoods.shp", quiet = TRUE) %>%
rename(neighborhood = "BDNAME")
mpls_all <- mpls_nbhd %>%
left_join(MplsDemo, by = c("neighborhood")) %>%
left_join(mpls_suspicious, by = c("neighborhood"))
leaflet to create a map from the mpls_all data that colors the neighborhoods by prop_suspicious. Display the neighborhood name as you scroll over it. Describe what you observe in the map.#pal_mpls <- colorFactor("viridis", domain = mpls_all$neighborhood)
#leaflet(mpls_all) %>%
#addTiles() %>%
#addPolygons(
#fillColor = ~pal(neighborhood),
#fillOpacity = 0.7)
leaflet to create a map of your own choosing. Come up with a question you want to try to answer and use the map to help answer that question. Describe what your map shows.\(~\)
DID YOU REMEMBER TO UNCOMMENT THE OPTIONS AT THE TOP?